// 导入加密数据
const bcrypt = require("bcryptjs");
// 生成token库
const jwt = require("jsonwebtoken")
const db = require("../db/index")
const config = require("../config/index")


exports.register = (req, res) => {
    const user = req.body
    // 对密码进行加密
    user.password = bcrypt.hashSync(user.password, 10)
    console.log(user)
    const sql = "SELECT * FROM user WHERE username = ?"
    db.query(sql, user.username, (err, ret) => {
        if (err) {
            console.log(err.sqlMessage)
            return res.cc(err.sqlMessage)
        }
        if (!ret.length) {
            const insertSql = "INSERT INTO user SET ?"
            db.query(insertSql, user, (err, ret) => {
                if (err) {
                    console.log(err.sqlMessage)
                    return res.cc(err.sqlMessage)
                }
                if (ret.affectedRows !== 1) {
                    return res.cc("注册失败,稍后尝试")
                }
                res.send({
                    status: 200,
                    msg: "注册用户成功"
                })
            })
        } else {
            return res.cc("该用户名已经被占用")
        }
    })
}

exports.login = (req, res) => {
    const sql = "SELECT * FROM user WHERE username = ?"
    db.query(sql, req.body.username, (err, ret) => {
        if (err)
            return res.cc(err.sqlMessage)
        if (ret.length === 0)
            return res.cc("该用户不存在")
        else if (ret.length === 1) {
            //对密码进行解密
            const flag = bcrypt.compareSync(req.body.password, ret[0].password)
            if (!flag)
                return res.cc("密码错误!")
            // 生成token
            const user = {
                ...ret[0],
                password: ''
            }
            user.token = jwt.sign(user, config.jwtSecretKey, {
                expiresIn: config.expiresIn
            })
            req.myuser = user
            return res.json({
                status: 200,
                data: user
            })
        } else {
            return res.cc("登录失败,请联系管理员")
        }
    })
}

exports.order = (req, res) => {
    const sql = "SELECT * FROM borrow_record"
}